/**
 * Created by zhangxiaoyu on 16/12/09.
 */
angular.module('hyt.signCtrl',[])

  .controller('notSignCtrl',function($scope,$filter,$ionicModal,Storage,SignList,$state){
    $scope.showloading=true;
    var loginMsg=Storage.get('user');
    $scope.signSearch={
      parameter:{
        status:'3',
        WAYBILL_NO:'',
        TRANSPORT_START:'',
        TRANSPORT_END:''
      },
      userMsg:{
        username:loginMsg.username,
        password:loginMsg.password,
        uuid:loginMsg.uuid
      }
    };
    SignList.getSignData($scope.signSearch);
    $scope.$on('SignList.Updated', function() {
      $scope.signData=SignList.getResult();
      $scope.showloading=false;
    });
    //下拉刷新
    $scope.doRefresh=function(){
      SignList.getSignData($scope.signSearch);
      $scope.$broadcast('scroll.refreshComplete');
    };
    //上拉加载更多
    $scope.loadMore=function(){
      SignList.getMoreSignData($scope.signSearch);
      $scope.$broadcast('scroll.infiniteScrollComplete');
    };
    //下一页
    $scope.hasNextPage = function() {
      return SignList.hasNextPage();
    };
    var t = new Date();
    var iToDay=t.getDate();
    var iToMon=t.getMonth();
    var iToYear=t.getFullYear();
    var iTDate=new Date(iToYear,iToMon,(iToDay-30));
    $scope.startDate=$filter('date')(iTDate,'yyyy-MM-dd');
    $scope.showStartDate = function() { //选择日期
      var optionsStart = {
        date: iTDate,
        mode: 'date',
        maxDate: new Date($scope.endDate) - 10000
      };
      datePicker.show(optionsStart, function(d) {
        if (!isNaN(d.getTime())) {  // valid date
          $scope.$apply(function () {
            iTDate=d;
            $scope.startDate = $filter('date')(iTDate,'yyyy-MM-dd');
          });
        }
      });
    };
    $scope.endDate=$filter('date')(new Date(),'yyyy-MM-dd');
    $scope.showEndDate = function(){
      console.log('EndDate');
      var optionsEnd = {
        date : new Date(),
        mode : 'date',
        minDate: new Date($scope.startDate) - 10000
      };
      datePicker.show(optionsEnd,function(d) {
        if (!isNaN(d.getTime())) {  // valid date
          $scope.$apply(function () {
            endTime=d;
            $scope.endDate = $filter('date')(endTime,'yyyy-MM-dd');
          });
        }
      });
    };
    $scope.searchSign=function(){
      $scope.signSearch.parameter.TRANSPORT_START=$scope.startDate;
      $scope.signSearch.parameter.TRANSPORT_END=$scope.endDate;
      SignList.getSignData($scope.signSearch);
      $scope.modal.hide();
    };
    $ionicModal.fromTemplateUrl('templates/tab-workbench/sign/searchSign.html', {
      scope: $scope
    }).then(function(modal) {
      $scope.modal = modal;
    });
    $scope.goDetail=function(id,STATUS){
      Storage.set('wayId',id);
      $state.go('detailTab.detail',{STATUS:STATUS});
    };
  })
  .controller('alreadySignCtrl',function($scope,$filter,$ionicModal,Storage,SignList,$state){
    $scope.showloading=true;
    var loginMsg=Storage.get('user');
    $scope.signSearch={
      parameter:{
        status:'6',
        WAYBILL_NO:'',
        WAYBILL_DATE_S:'',
        WAYBILL_DATE_E:''
      },
      userMsg:{
        username:loginMsg.username,
        password:loginMsg.password,
        uuid:loginMsg.uuid
      }
    };
    SignList.getSignData($scope.signSearch);
    $scope.$on('SignList.Updated', function() {
      $scope.signData=SignList.getResult();
      $scope.showloading=false;
    });
    //下拉刷新
    $scope.doRefresh=function(){
      SignList.getSignData($scope.signSearch);
      $scope.$broadcast('scroll.refreshComplete');
    };
    //上拉加载更多
    $scope.loadMore=function(){
      SignList.getMoreSignData($scope.signSearch);
      $scope.$broadcast('scroll.infiniteScrollComplete');
    };
    //下一页
    $scope.hasNextPage = function() {
      return SignList.hasNextPage();
    };
    var t = new Date();
    var iToDay=t.getDate();
    var iToMon=t.getMonth();
    var iToYear=t.getFullYear();
    var iTDate=new Date(iToYear,iToMon,(iToDay-30));
    $scope.startDate=$filter('date')(iTDate,'yyyy-MM-dd');
    $scope.showStartDate = function() { //选择日期
      var optionsStart = {
        date: iTDate,
        mode: 'date',
        maxDate: new Date($scope.endDate) - 10000
      };
      datePicker.show(optionsStart, function(d) {
        if (!isNaN(d.getTime())) {  // valid date
          $scope.$apply(function () {
            iTDate=d;
            $scope.startDate = $filter('date')(iTDate,'yyyy-MM-dd');
          });
        }
      });
    };
    $scope.endDate=$filter('date')(new Date(),'yyyy-MM-dd');
    $scope.showEndDate = function(){
      console.log('EndDate');
      var optionsEnd = {
        date : new Date(),
        mode : 'date',
        minDate: new Date($scope.startDate) - 10000
      };
      datePicker.show(optionsEnd,function(d) {
        if (!isNaN(d.getTime())) {  // valid date
          $scope.$apply(function () {
            endTime=d;
            $scope.endDate = $filter('date')(endTime,'yyyy-MM-dd');
          });
        }
      });
    };
    $scope.searchSign=function(){
      $scope.signSearch.parameter.WAYBILL_DATE_S=$scope.startDate;
      $scope.signSearch.parameter.WAYBILL_DATE_E=$scope.endDate;
      SignList.getSignData($scope.signSearch);
      $scope.modal.hide();
    };
    $ionicModal.fromTemplateUrl('templates/tab-workbench/sign/searchSign.html', {
      scope: $scope
    }).then(function(modal) {
      $scope.modal = modal;
    });
    $scope.goDetail=function(id,STATUS){
      Storage.set('wayId',id);
      $state.go('detailTab.detail',{STATUS:STATUS});
    };
  })
  .controller('signMsgCtrl',function($scope,$filter,$ionicModal,$stateParams,Storage,SignWaybill,$ionicLoading,$state){
    var loginMsg=Storage.get('user');
    $scope.signMsg={
      ids:[
          $stateParams.id
      ],
      signaMap:{
        signatoryName:$stateParams.CONSIGNEE,
        signatoryNumber:'',
        signatoryDate:$filter('date')(new Date(),'yyyy-MM-dd HH:mm:ss')
      },
      userMsg:{
        username:loginMsg.username,
        password:loginMsg.password,
        uuid:loginMsg.uuid
      }
    };
    //选择签收日期
    $scope.signDate = function() { //选择日期
      var optionsStart = {
        date:$scope.signMsg.signaMap.signatoryDate,
        mode: 'date'
      };
      datePicker.show(optionsStart, function(d) {
        if (!isNaN(d.getTime())) {  // valid date
          $scope.$apply(function () {
            $scope.signMsg.signaMap.signatoryDate = $filter('date')(d,'yyyy-MM-dd HH:mm:ss');
          });
        }
      });
    };

    $scope.signWaybill=function(){
      SignWaybill.getSignWaybill(JSON.stringify($scope.signMsg));
      $scope.$on('SignWaybill.Updated', function() {
        var result=SignWaybill.getResult();
        if (result.success==true){
          $ionicLoading.show({
            noBackdrop: true,
            template: result.msg,
            duration: 1500
          });
          $state.go('signTab.not');
        }
      })
    }
  })
  .controller('recoveryCtrl',function($scope,$filter,$ionicModal,$stateParams,Storage,Recovery,$ionicLoading,$state,$ionicActionSheet,$cordovaCamera,$cordovaImagePicker,$ionicPopup,UploadReceiptImg){
    var loginMsg=Storage.get('user');
    var userMsg=Storage.get('loginResult');
    $scope.recoveryMsg={
      RECEIPT_NUM:$stateParams.RECEIPT_NUM,
      cname:userMsg.rows.cname
    };
    var upImg={
      wayBillId:$stateParams.id,
      fileName:'',
      fileContext:''
    };
    var imgPic=[];
    $scope.imgData=[];
    $scope.actionSheet=function(){
      var hideSheet = $ionicActionSheet.show({
        buttons: [
          { text: '拍照' },
          { text: '从相册选择' }
        ],
        cancelText: '取消',
        cancel: function() {
          // add cancel code..
        },
        buttonClicked: function(index) {
          if(index==0){
            var options = {
              destinationType: Camera.DestinationType.NATIVE_URI,
              sourceType: Camera.PictureSourceType.CAMERA,
              targetWidth: 800,
              targetHeight: 800
            };

            $cordovaCamera.getPicture(options).then(function(imageURI) {
              if (imgPic.length>2){
                $ionicLoading.show({
                  noBackdrop: true,
                  template: "最多支持三张照片",
                  duration: 1500
                });
              }else {
                imgPic[imgPic.length]= imageURI;
              }
            }, function(err) {
              // error
            });
          }else if (index==1){
            var options = {
              maximumImagesCount: 10,
              width: 800,
              height: 800,
              quality: 80
            };

            $cordovaImagePicker.getPictures(options)
              .then(function (results) {
                if (imgPic.length+results.length>3){
                  $ionicLoading.show({
                    noBackdrop: true,
                    template: "最多支持三张照片",
                    duration: 1500
                  });
                }else {
                  for (var i = 0,j=imgPic.length; i < results.length; i++,j++) {
                    imgPic[j]=results[i];
                  }
                }
              }, function(error) {
                // error getting photos
              });
          }
          $scope.imgData=imgPic;

          return true;
        }
      });
    };
    $scope.deleteImg=function(img){
      var j;
      var receipt = $ionicPopup.confirm({
        title : '是否删除图片',
        cancelText : '否',
        cancelType : 'button-stable',
        okText : '是'
      });
      receipt.then(function(r){
        if(r){
          for (var i=0;i<$scope.imgData.length;i++){
            if ($scope.imgData[i]==img){
              j=i;
              $scope.imgData.splice(j,1);
            }
          }
        }else{
          console.log('取消');
        }
      });
    };
    $scope.recoveryRct=function(){
      var receiptId={
        id:$stateParams.id,
        userMsg:{
          username:loginMsg.username,
          password:loginMsg.password,
          uuid:loginMsg.uuid
        }
      };
      Recovery.getRecovery(JSON.stringify(receiptId));
      $scope.$on('Recovery.Updated', function() {
        var result=Recovery.getResult();
        if (result.success==true){
          uploadImg();
          $ionicLoading.show({
            noBackdrop: true,
            template: result.rows,
            duration: 1500
          });
          $state.go('signTab.already');
        }
      });
    };
    function uploadImg(){
      for (var i=0;i<$scope.imgData.length;i++){
        var canvas = document.createElement('CANVAS');
        var ctx = canvas.getContext('2d');
        var dataURL;
        var img = new Image();
        img.crossOrigin = 'Anonymous';
        img.src = $scope.imgData[i];
        img.onload = function(){
          canvas.height = this.height;
          canvas.width = this.width;
          ctx.drawImage(this,0,0,this.width,this.height);
          var ext = this.src.substring(this.src.lastIndexOf(".")+1).toLowerCase();
          var extendName = this.src.substring(this.src.lastIndexOf("/")+1).toLowerCase();
          dataURL = canvas.toDataURL("image/"+ext);
          upImg.fileName=extendName;
          upImg.fileContext=dataURL;
          UploadReceiptImg.getUpImg(upImg);
        };
      }
    }
  })
